package org.codeart.ioc.util;

import java.io.File;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class AnnotationUtil {

    /**
     * 在某个路径下扫描被某个注解修饰的所有字节码对象
     * @param packagePath   类路径
     * @param annotation    修饰类的注解
     * @return  字节码对象列表
     */
    public static List<Class<?>> scanComponents(String packagePath, Class<? extends Annotation> annotation) {
        List<Class<?>> componentClasses = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packagePath.replace('.', '/');
        URL resource = classLoader.getResource(path);
        if (resource == null) {
            throw new IllegalArgumentException("Package not found: " + packagePath);
        }
        File directory = new File(resource.getFile());
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        componentClasses.addAll(scanComponents(packagePath + "." + file.getName(), annotation));
                    } else if (file.getName().endsWith(".class")) {
                        String className = packagePath + '.' + file.getName().substring(0, file.getName().length() - 6);
                        try {
                            Class<?> clazz = Class.forName(className);
                            if (clazz.isAnnotationPresent(annotation)) {
                                componentClasses.add(clazz);
                            }
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return componentClasses;
    }

}
